package com.pic;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.app.BaseActivity;
import com.example.com.skills_utf8.R;

import java.io.File;
import java.io.FileOutputStream;

import m.framework.utils.Utils;

public class PicClipActivity extends BaseActivity {


    PicClipActivity activity = this;

    Handler hanlder = new Handler();


    ImageView iv_bg;
    ImageView iv_clip;


    @Override
    public Integer InitLayout() {
        return R.layout.activity_pic;
    }

    @Override
    public void InitView() {

         iv_bg = (ImageView)findViewById(R.id.iv_bg);
         iv_clip = (ImageView)findViewById(R.id.iv_clip);



        Button btn_save = (Button)findViewById(R.id.btn_save);
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                BitmapDrawable drawable = (BitmapDrawable) iv_bg.getBackground();
                Bitmap bitmap_source = drawable.getBitmap();

                int[] position_src = new int[2];
                int[] position = new int[2];
                iv_bg.getLocationOnScreen(position_src);
                iv_clip.getLocationOnScreen(position);


                int x_new = position[0] - position_src[0];
                int y_new = position[1] - position_src[1];
                int width = iv_clip.getMeasuredWidth();
                int height = iv_clip.getMeasuredHeight();


                Bitmap bitmap = Bitmap.createBitmap(bitmap_source, x_new, y_new, width, height);
                saveBitmap(bitmap);


            }
        });


        Button btn_left = (Button)findViewById(R.id.btn_left);
        Button btn_right = (Button)findViewById(R.id.btn_right);
        Button btn_clip = (Button)findViewById(R.id.btn_clip);

        btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int x_delta = -10;
                ///* view没有做到平移被缩放了;
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) iv_clip.getLayoutParams();
                // params是个引用，所以值能被动态改变；
                params.leftMargin = params.leftMargin + (int)x_delta;
                //       params.topMargin = params.topMargin + (int)y_delta;
                //       params.bottomMargin = params.bottomMargin + (int)y_delta;
                iv_clip.setLayoutParams(params);
                //*/
            }
        });

        btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int x_delta = 10;

                ///* view没有做到平移被缩放了;
                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) iv_clip.getLayoutParams();
                // params是个引用，所以值能被动态改变；
                params.leftMargin = params.leftMargin + (int) x_delta;
                //       params.topMargin = params.topMargin + (int)y_delta;
                iv_clip.setLayoutParams(params);
                //*/
            }
        });

        btn_clip.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {


                BitmapDrawable drawable = (BitmapDrawable) iv_bg.getBackground();
                Bitmap bitmap_source = drawable.getBitmap();

                BitmapDrawable drawable_dest = (BitmapDrawable) iv_clip.getBackground();
                Bitmap bitmap_dest = drawable_dest.getBitmap();
                //     NinePatchDrawable drawable_dest = (NinePatchDrawable)iv_clip.getBackground();
                //     Bitmap bitmap_dest = drawable2Bitmap(drawable_dest);


                Paint paint_base = new Paint();
                paint_base.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR));
                //    paint_base.setStyle(Paint.Style.STROKE);
                //    paint_base.setAlpha( 75 );


                //      int width = Utils.getScreenWidth(activity);
                //      int height = Utils.getScreenWidth(activity);
                //     int width = iv_bg.getMeasuredWidth();
                //     int height = iv_bg.getMeasuredHeight();

                /*
                // 设置半透明背景
                Bitmap bitmap_base = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                setTranslateColor(bitmap_base);
                saveBitmap(bitmap_base);
                */


                /*
                Bitmap bitmap_base = Bitmap.createBitmap(bitmap_source);  //
                Canvas canvas = new Canvas(bitmap_base);
                canvas.drawBitmap(bitmap_source, 0,0,paint_base);   // 使背景中间镂空
                canvas.drawBitmap(bitmap_dest, 0, 0, new Paint());  // 绘制目标到位图


                iv_bg.setBackgroundColor(0);
                iv_bg.setImageBitmap(bitmap_base);
                */


                ///*
                FrameLayout layout_clip = (FrameLayout) findViewById(R.id.layout_clip);
                BitmapDrawable drawable_layout = (BitmapDrawable) layout_clip.getBackground();
                Bitmap bitmap_layout = (Bitmap) drawable_layout.getBitmap();
                //     ColorDrawable drawable_layout = (ColorDrawable)framelayout.getBackground();
                //     Bitmap bitmap_layout = drawableToBitmap( drawable_layout );

                Bitmap bitmap_layout_new = Bitmap.createBitmap(bitmap_layout.getWidth(), bitmap_layout.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap_layout_new);
                canvas.drawBitmap(bitmap_layout,0,0,null);
                saveBitmap(bitmap_layout_new, "half_translate");    // 保存为半透明的全图


                int[] position_src = new int[2];
                int[] position = new int[2];
                layout_clip.getLocationOnScreen(position_src);
                iv_clip.getLocationOnScreen(position);


                int x_new = position[0] - position_src[0];
                int y_new = position[1] - position_src[1];
                int width = iv_clip.getMeasuredWidth();
                int height = iv_clip.getMeasuredHeight();



                drawTranslateColor(bitmap_layout_new, x_new, y_new, width, height);
                saveBitmap(bitmap_layout_new, "do");   // 保存中间为透明的全图；


                //以上达到修改背景的目的，如果以上成功，将位图放置到该背景，那么就成功达到目的修改背景的目的；
                BitmapDrawable bd=new BitmapDrawable(bitmap_dest);
                layout_clip.setBackground((Drawable)bd);
//*/


            }
        });




    }




    //
    void drawTranslateColor(Bitmap bitmap, int x, int y, int width, int height){

        for(int i =y; i<y+height; i++){
            for(int j =x; j<x+width; j++){
                bitmap.setPixel(j,i, Color.TRANSPARENT);
            }
        }

    }




    void setTranslateColor(Bitmap bitmap){
        for(int i =0; i<bitmap.getHeight(); i++){
            for(int j =0; j<bitmap.getWidth(); j++){
                int pixel = bitmap.getPixel(j,i);
                pixel = pixel | 0xaa000000;
                bitmap.setPixel(j,i,pixel);
            }
        }

    }


    /**
     * Drawable 转 bitmap
     * @param drawable
     * @return
     */
    public static Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else {
            return null;
        }
    }


        @Override
    public void InitListener() {

    }

    @Override
    public void InitProcess() {




    }


    float x_last =0;
    float y_last =0;

    Matrix matrix = new Matrix();

    int[] position_src = new int[2];
    int[] position = new int[2];


    @Override
    public boolean onTouchEvent(MotionEvent event) {


        float x = event.getRawX();
        float y = event.getRawY();



        iv_bg.getLocationOnScreen(position_src);


        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
                x_last = x;
                y_last = y;
                break;
            case MotionEvent.ACTION_MOVE:

                float x_delta = x - x_last;
                float y_delta = y - y_last;

                System.out.println("x_delta: "+x_delta);
                System.out.println("y_delta: "+y_delta);


                iv_clip.getLocationOnScreen(position);

                position[0] += x_delta;
                position[1] += y_delta;

                int src_width = position_src[0] + iv_bg.getMeasuredWidth();
                int src_height = position_src[1] + iv_bg.getMeasuredHeight();

                int width = position[0] + iv_clip.getMeasuredWidth() ;
                int height = position[1] + iv_clip.getMeasuredHeight() ;



                FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) iv_clip.getLayoutParams();
                // params是个引用，所以值能被动态改变；
                if(position[0] > position_src[0] && width < src_width)  //
                    params.leftMargin = params.leftMargin + (int)x_delta;
                if(position[1] > position_src[1] && height < src_height)
                   params.topMargin = params.topMargin + (int)y_delta;
         //       params.rightMargin = params.rightMargin + (int)x_delta;
         //       params.bottomMargin = params.bottomMargin + (int)y_delta;
                iv_clip.setLayoutParams(params);
                //*/


                /*
                iv_clip.setScaleType(ImageView.ScaleType.MATRIX);
                matrix.postTranslate(x_delta, y_delta);
                iv_clip.setImageMatrix(matrix);
                */



                /*
                BitmapDrawable drawable = (BitmapDrawable) iv_bg.getBackground();
                Bitmap bitmap_source = drawable.getBitmap();


                // 使指定位置显示图像， 大背景显示半透明
                Paint paint = new Paint();
                paint.setStyle(Paint.Style.STROKE);
                paint.setAlpha(50);


                Canvas canvas = new Canvas(bitmap_source);
                canvas.drawBitmap(bitmap_source, ); // 绘制背景半透明
                */



                x_last = x;
                y_last = y;

                break;
        }


        return true;


    }


    void change(){

    }

    /**
     * 保存图片到SD卡上
     */
    protected void saveBitmap(Bitmap baseBitmap) {
        try {

            String appname = getResources().getString(R.string.app_name);
            appname = appname + "_";

            // 保存图片到SD卡上
            File file = new File(Environment.getExternalStorageDirectory(),
                    appname+System.currentTimeMillis() + ".png");
            FileOutputStream stream = new FileOutputStream(file);
            baseBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            stream.close();
            ShowToast("保存图片成功");

        } catch (Exception e) {
            ShowToast("保存图片失败");
            e.printStackTrace();
        }
    }


    /**
     * 保存图片到SD卡上
     */
    protected void saveBitmap(Bitmap baseBitmap, String name) {
        try {

            // 保存图片到SD卡上
            File file = new File(Environment.getExternalStorageDirectory(),
                    name+System.currentTimeMillis() + ".png");
            FileOutputStream stream = new FileOutputStream(file);
            baseBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            stream.close();
            ShowToast("保存图片成功");

        } catch (Exception e) {
            ShowToast("保存图片失败");
            e.printStackTrace();
        }
    }


}
